package com.formula.datastructure.exam.sort;

import com.formula.datastructure.util.DataUtil;

public class InsertSort {
    public Integer[] sort(Integer[] array) {
        int N = array.length;
        for (int i = 1; i < N; i++) {
            int idx = i;
            Integer insert = array[i];
            for (int j = i - 1; j >= 0; j--) { // 注意j是减
                if (insert < array[j]) {
                    array[j + 1] = array[j];
                    idx = j;
                } else {
                    break; //千万记住
                }
            }
            if (idx != i) {
                array[idx] = insert;
            }
        }
        return array;
    }

    public static void main(String[] args) {
        InsertSort insert = new InsertSort();

        int size = 20;
        int range = 999;
        Integer[] array = DataUtil.genUniqueArray(size, range);
        DataUtil.printIndex(size);
        DataUtil.printArray(array);
        DataUtil.printArray(insert.sort(array));
    }
}
